package com.ruicar.afs.cloud.basic.cms.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruicar.afs.cloud.afscase.dispatch.contract.CmsInterfaceFeign;
import com.ruicar.afs.cloud.basic.common.condition.DeductionInfoChildCondition;
import com.ruicar.afs.cloud.basic.common.condition.QueryCustInfoMultipleCondition;
import com.ruicar.afs.cloud.basic.common.service.BasicRepaymentPlanService;
import com.ruicar.afs.cloud.basic.feign.ApplyFeign;
import com.ruicar.afs.cloud.common.config.ContractFeginConfig;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.apply.dto.ApplyIdCardDTO;
import com.ruicar.afs.cloud.common.modules.apply.dto.ApplyIdCardInfoDTO;
import com.ruicar.afs.cloud.common.modules.contract.cms.vo.CmsProgressInquiryDataVo;
import com.ruicar.afs.cloud.common.modules.contract.cms.vo.LoanProgressVo;
import com.ruicar.afs.cloud.common.modules.contract.enums.ContractFeginParamEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.ContractStatusEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.CustTypeEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.PersonRoleTypeEnum;
import com.ruicar.afs.cloud.common.util.EmptyUtils;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: Lee
 * @date: 2020/5/11 19:39
 * @description: 品合同对接聚合层 贷款进度查询接口
 */
@Slf4j
@RestController
@RequestMapping("/icosLoanProgress")
@AllArgsConstructor
public class IcosLoanProgressController {

    private final BasicRepaymentPlanService basicRepaymentPlanService;
    private final CmsInterfaceFeign cmsInterfaceFeign;
    private final ContractFeginConfig contractFeginConfig;
    private final ApplyFeign applyFeign;

    @ApiOperation(value = "2.2贷款进度查询接口(接口聚合使用)")
    @PostMapping("/getLoanProgress")
    public IResponse<JSONObject> getLoanProgress(@RequestParam(value="certNo", defaultValue = "") String certNo,
                                                            @RequestParam(value="applyNo",required = false) String applyNo){
        log.info("-------------------2.2贷款进度查询接口,传入值证件号:[{}]，申请编号:[{}]-------------------",certNo,applyNo);
        if((EmptyUtils.isEmpty(certNo)||"null".equals(certNo))&&(EmptyUtils.isEmpty(applyNo)||"null".equals(applyNo))){
            return IResponse.fail("身份证号、申请号不能同时为空");
        }
        if("null".equals(certNo)){
            certNo = null;
        }
        CmsProgressInquiryDataVo loan = new CmsProgressInquiryDataVo();

        QueryCustInfoMultipleCondition condition = new QueryCustInfoMultipleCondition();
        condition.setCustRole(AfsEnumUtil.key(PersonRoleTypeEnum.MAIN_PERSON));
        if(EmptyUtils.isEmpty(certNo)){
            condition.setApplyNo(applyNo);
        }else{
            condition.setCertNo(certNo);
            loan.setIdCard(certNo);
        }
        String ct = certNo;
        List<DeductionInfoChildCondition> deductionInfoChildConditions = basicRepaymentPlanService.deductionInfo(condition);
        List<LoanProgressVo> loanProgressVos = JSON.parseArray(JSON.toJSONString(deductionInfoChildConditions), LoanProgressVo.class);
        if(EmptyUtils.isNotEmpty(loanProgressVos)){
            ct = loanProgressVos.get(0).getCertNo();
        }
        //调用贷前数据接口
        Map map = new HashMap();
        map.put(AfsEnumUtil.key(ContractFeginParamEnum.CASE_CLIENT_SECRET),contractFeginConfig.getCaseClientSecret());
        map.put(AfsEnumUtil.key(ContractFeginParamEnum.CASE_CLIENT_ID),contractFeginConfig.getCaseClientId());
        map.put(AfsEnumUtil.key(ContractFeginParamEnum.CONTENT_TYPE), MediaType.APPLICATION_JSON_VALUE);
        IResponse<CmsProgressInquiryDataVo> response = cmsInterfaceFeign.getLoanProgress(certNo, applyNo, map);
        log.info("-------------------2.2贷款进度查询接口,获取贷前数据结果，code:[{}],msg:[{}],data:[{}]-------------------",response.getCode(),response.getMsg(),response.getData());
        if(CommonConstants.SUCCESS.equals(response.getCode())&&EmptyUtils.isNotEmpty(response.getData())&&EmptyUtils.isNotEmpty(response.getData().getApphis())&&response.getData().getApphis().size()>0){
            if(EmptyUtils.isNotEmpty(response.getData().getIdCard())){
                ct = response.getData().getIdCard();
            }
            loanProgressVos.addAll(response.getData().getApphis());
        }
        loan.setIdCard(ct);
        loan.setApphis(loanProgressVos);
        return IResponse.success(loan);
    }


    @ApiOperation(value = "身份验证  根据身份证号或者合同号码查询客户手机号信息（包含贷前数据）（CMS接口聚合使用）")
    @PostMapping("/getCustPhone")
    public IResponse<ApplyIdCardInfoDTO> getCustPhone(@RequestParam(value="certNo",required = false) String certNo,
                                                         @RequestParam(value="contractNo",required = false) String contractNo){
        ApplyIdCardInfoDTO verificationCondition = new ApplyIdCardInfoDTO();
        log.info("-------------------身份验证,传入值证件号:[{}]，申请编号:[{}]-------------------",certNo,contractNo);
        if((EmptyUtils.isEmpty(certNo)||"null".equals(certNo))&&(EmptyUtils.isEmpty(contractNo)||"null".equals(contractNo))){
            return IResponse.fail("身份证号、合同号不能同时为空");
        }
        verificationCondition.setSpecialStatus(null);
        verificationCondition.setOriginalPhone(null);

        QueryCustInfoMultipleCondition condition = new QueryCustInfoMultipleCondition();
        condition.setCustRole(PersonRoleTypeEnum.MAIN_PERSON.name());
        if(EmptyUtils.isEmpty(certNo)||"null".equals(certNo)){
            condition.setContractNo(contractNo);
        }else{
            condition.setCertNo(certNo);
            verificationCondition.setIdCard(certNo);
        }
        List<DeductionInfoChildCondition> deductionInfoChildConditions = basicRepaymentPlanService.deductionInfo(condition);
        log.info("-------------------身份验证,贷后取到的输出结果为：[{}]-------------------",deductionInfoChildConditions);
        if(EmptyUtils.isNotEmpty(deductionInfoChildConditions)&&deductionInfoChildConditions.size()>0){
            verificationCondition.setCustomerStatus("1");
            verificationCondition.setOriginalPhone(deductionInfoChildConditions.get(0).getPhone());
            verificationCondition.setIdCard(deductionInfoChildConditions.get(0).getCertNo());
            for (DeductionInfoChildCondition cd : deductionInfoChildConditions) {
                if(ContractStatusEnum.contractCancel.name().equals(cd.getPayStatus())){
                    verificationCondition.setSpecialStatus("4");
                }else if(ContractStatusEnum.writeOff.name().equals(cd.getPayStatus())){
                    verificationCondition.setSpecialStatus("2");
                }else{
                    verificationCondition.setSpecialStatus("1");
                }
            }
        }

        //贷前数据
        Map<String, String> headers = new HashMap<>();
        headers.put(AfsEnumUtil.key(ContractFeginParamEnum.APPLY_CLIENT_ID), contractFeginConfig.getApplyClientId());
        headers.put(AfsEnumUtil.key(ContractFeginParamEnum.APPLY_CLIENT_SECRET), contractFeginConfig.getApplyClientSecret());
        headers.put(AfsEnumUtil.key(ContractFeginParamEnum.CONTENT_TYPE), MediaType.APPLICATION_JSON_VALUE);
        ApplyIdCardDTO dto = new ApplyIdCardDTO();
        dto.setApplicationNo(contractNo);
        dto.setIdCard(certNo);
        IResponse<ApplyIdCardInfoDTO> idCardInfo = applyFeign.getIdCardInfo(dto, headers);
        log.info("-------------------身份验证,贷前查询取到的输出结果为,code:[{}],msg:[{}],data:[{}]-------------------",idCardInfo.getCode(),idCardInfo.getMsg(),idCardInfo.getData());

        if(CommonConstants.SUCCESS.equals(idCardInfo.getCode())){
            //贷后数据优先
            if(EmptyUtils.isEmpty(verificationCondition.getIdCard())){
                verificationCondition.setIdCard(idCardInfo.getData().getIdCard());
            }
            if(EmptyUtils.isEmpty(verificationCondition.getSpecialStatus())){
                verificationCondition.setSpecialStatus(idCardInfo.getData().getSpecialStatus());
            }
            String originalPhone = idCardInfo.getData().getOriginalPhone();
            //贷后有查到客户手机号，则把两边的结果拼接在一起
            if(EmptyUtils.isNotEmpty(verificationCondition.getOriginalPhone())){
                verificationCondition.setOriginalPhone(verificationCondition.getOriginalPhone()+","+originalPhone);
            }else{
                //只有贷前有数据则放入贷前的手机号数据
                verificationCondition.setOriginalPhone(originalPhone);
            }
        }
        //如果在多品系统没有查到手机号，则判断其不是公司客户,否则是公司客户
        if(EmptyUtils.isNotEmpty(verificationCondition.getOriginalPhone())&&verificationCondition.getOriginalPhone().split(",").length>0){
            verificationCondition.setCustomerStatus("1");
        }else{
            verificationCondition.setCustomerStatus("2");
        }

        return IResponse.success(verificationCondition);
    }

    @ApiOperation(value = "通过身份证号获取所有合同")
    @PostMapping("/caseCount")
    public IResponse<List<LoanProgressVo>> caseCount(@RequestParam(value="certNo") String certNo){
        log.error("-------------------------通过身份证号获取所有合同入参值为：{}-------------------------",certNo);
        if(EmptyUtils.isEmpty(certNo)){
            return IResponse.fail("身份证号不能为空");
        }

        List<LoanProgressVo> loanProgressVos = new ArrayList<>();
        QueryCustInfoMultipleCondition condition = new QueryCustInfoMultipleCondition();
        condition.setCertNo(certNo);
        List<DeductionInfoChildCondition> deductionInfoChildConditions = basicRepaymentPlanService.deductionInfo(condition);
        log.info("-------------------------通过身份证号获取所有合同deductionInfoChildConditions查询到数据条数为：{}-------------------------",deductionInfoChildConditions);
        List<LoanProgressVo> afterLoanData = JSON.parseArray(JSON.toJSONString(deductionInfoChildConditions), LoanProgressVo.class);
        if(EmptyUtils.isNotEmpty(afterLoanData)){
            loanProgressVos.addAll(afterLoanData);
        }
        //贷前数据
        Map<String, String> headers = new HashMap<>();
        headers.put(AfsEnumUtil.key(ContractFeginParamEnum.CASE_CLIENT_SECRET),contractFeginConfig.getCaseClientSecret());
        headers.put(AfsEnumUtil.key(ContractFeginParamEnum.CASE_CLIENT_ID),contractFeginConfig.getCaseClientId());
        headers.put(AfsEnumUtil.key(ContractFeginParamEnum.CONTENT_TYPE), MediaType.APPLICATION_JSON_VALUE);
        IResponse<List<LoanProgressVo>> beforeLoanData = cmsInterfaceFeign.getAllContractsByCerNo(certNo, headers);
        log.info("-------------------------通过身份证号获取所有合同查询贷前数据结果为code:{},msg:{},data:{}-------------------------",beforeLoanData.getCode(),beforeLoanData.getMsg(),beforeLoanData.getData());
        if(CommonConstants.SUCCESS.equals(beforeLoanData.getCode())&&EmptyUtils.isNotEmpty(beforeLoanData.getData())&&beforeLoanData.getData().size()>0){
            loanProgressVos.addAll(beforeLoanData.getData());
        }
        if(EmptyUtils.isEmpty(loanProgressVos)){
            log.info("-------------------------通过身份证号获取所有合同没有查询到相关信息-------------------------");
            return IResponse.fail("没有查询到相关信息");
        }

        return IResponse.success(loanProgressVos);
    }



}
